<!-- 选择装具的图形化界面 -->
<template>
  <el-dialog title="选择装具" v-model="dialogVisible" width="60%" modal draggable :close-on-click-modal="false"
    :append-to-body="true" :before-close="handleClose">
    <span slot="title">
      <span style="font-size: 18px">选择装具</span>
      <hlepMessage v-show="UseDetails == 'newInventory'"
        messageText="选择整架：点击装具的空白位置可选中整列，选中整架，背景颜色会发生变化;<br>多选列/单选列：点击装具可选中，选中装具上会有选中的标识;<br选择库位：点击列后，再点击A面/左面或者B面/右面.可进入库位的选择界面，可自定义选择库位;">
      </hlepMessage>
    </span>
    <div class="cabint-body" v-for="(item, index) in cabinetList" :key="index" style="height: 40vh">
      <div class="cabint-body-center">
        <div class="zyTypeButton" v-show="UseDetails == 'newInventory' && isShowLeftAndRight(item.children)">
          <el-button size="medium" label="1" @click="changePadio('1')">{{
            zytypebutton == 0 ? 'A面' : '左面'
            }}</el-button>
          <el-button size="medium" label="2" @click="changePadio('2')">{{
            zytypebutton == 0 ? 'B面' : '右面'
            }}</el-button>
        </div>
        <!-- </el-radio-group> -->
        <div class="cabint" :ref="`cabint${index}`" @click="UseDetails == 'newInventory' && selectCabinet(item)" :class="{
          'Select-Cabint-Active':
            UseDetails == 'newInventory' && item.deviceId == SelectCabintActiveId,
        }">
          <!-- 'Select-Cabint-Active': UseDetails == 'newInventory'&& item == SelectCabintActive 加上判断：这个角标只有在盘点的时候才会出现，其他情况比如上下架的情况不可以出现 -->
          <i v-show="item.deviceId == SelectCabintActiveId" class="iconfont icon-jiaobiaoxuanzhong jiaobiao"></i>

          <div v-for="x in item.children" :key="x.deviceId" :class="{ isActive: x == currentIndex }" class="mjj-box"
            :style="[
              {
                width: '0.6rem',
                background: `linear-gradient(#ffffff ${100 - percentage(x)}%, #15a8ea 0%)`,
                '--gradient-start': 100 - percentage(x) + '%',
              },
            ]" style="width: 0.6rem; background: #fff" @click="oneSelectMjj(null, x)">
            <i class="iconfont icon-choose choose" v-show="UseDetails == 'newInventory' && isSelected(x)"></i>
            <em class="mjj-text" :style="{ top: lessThan90(percentage(x)) + '%' }">{{ percentage(x) }}%</em>
            <em class="mjj-text" :style="{
              top: '27%',
              color: '#ff0604',
              fontSize: '0.1rem',
            }" style="font-family: DSDIGIT">{{ formattedFourDigitNumber(x.colNo) }}</em>
            <img slot="reference" v-if="x.fixedFlag == 1" :src="`${item.fixedColUrl
              ? `${uploadURL}/mjj/${item.fixedColUrl}`
              : getLocalImageUrl(x.fixedFlag)
              }`" class="mjj-img no-select" style="width: 100%; height: 100%" />
            <img v-else :src="`${item.moveColUrl ? `${uploadURL}/mjj/${item.moveColUrl} ` : getLocalImageUrl()
              }`" slot="reference" class="mjj-img no-select" style="width: 100%; height: 100%" />
          </div>
        </div>
      </div>
      <div style="margin: 0 auto; width: 60%; text-align: center">
        <span style="font-weight: 700">{{ item.deviceName }}</span> 共<span class="heightLight-text">{{
          item.children.length }}</span>列
      </div>
    </div>
    <colDetails ref="colDetails" :colItem="colItem" @handleClose="handleClose" :upItemWidth="upItemWidth"></colDetails>
    <InventoryColDetails ref="InventoryColDetails" :colItem="colItem" @handleClose="handleClose"
      :upItemWidth="upItemWidth"></InventoryColDetails>
    <div slot="footer" class="dialog-footer" v-show="UseDetails == 'newInventory'">
      <el-button @click="handleClose" size="medium">取 消</el-button>
      <el-button type="primary" @click="submitForm" size="medium">
        {{ SelectCabintActiveId ? '盘点整架' : '盘点选中列' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import colDetails from '@/views/VirtualHouse/colDetails.vue'
import InventoryColDetails from '@/views/VirtualHouse/InventoryColDetails.vue'
// import { EventBus } from '@/utils/EventBus'
import Decimal from 'decimal.js'

export default {
  name: 'choiceCabinet',
  components: { colDetails, InventoryColDetails },
  props: {
    cabinetList: {
      type: Array,
      default: () => [],
    },
    data: {
      type: Array,
      default: () => [],
    },
    UseDetails: {
      type: String,
      default: ' ',
    },
  },
  data() {
    return {
      dialogVisible: false,
      currentIndex: null,
      colItem: null,
      showColItemData: false,
      upItemWidth: 0,
      SelectCabintActive: null,
      SelectCabintActiveId: null,
      zyType: '',
      // 已经选择的架子
      selectedMJJ: [],
      selectCabinets: [], //0为整架 1为列
      // 提交的标识
      zytypebutton: 0,
    }
  },
  computed: {
    isSelected() {
      return function (val) {
        const result = this.selectedMJJ.some((item) => JSON.stringify(item) === JSON.stringify(val))
        return result
      }
    },
    formattedFourDigitNumber() {
      /**
       * 格式化数字为四位数。如果数字本身是1-999之间的数，
       * 则在其前面补足零至四位；如果是四位数或以上，则直接返回该数字。
       */

      return function (val) {
        const numStr = String(val)
        const paddingLength = 4 - numStr.length
        // 确保只对不足四位的数字进行补零
        return paddingLength > 0 ? `0`.repeat(paddingLength) + numStr : numStr
      }
    },

    // 剩余空间
    surplusSpace() {
      // 剩余空间 = (1- (盒总宽总计 / 库位总宽度))*100%
      return function (val) {
        const allDivWidth = val.allDivWidth === 0 ? 1 : val.allDivWidth
        return Decimal(1)
          .sub(new Decimal(val.allBoxWidth).div(new Decimal(allDivWidth)))
          .mul(100)
          .toFixed(2)
      }
    },
    // 密集架中的百分比
    percentage() {
      return function (val) {
        // 除数做判断，不能为0
        if (val) {
          const cmPageNo = JSON.parse(localStorage.getItem('cmPageNo'))
          /**
           * val.pageNoCount 档案的页数  cmPageNo  定义的档案多少页为一厘米
           * val.pageNoCount / cmPageNo  档案一共占据了多少里面
           * val.allBoxWidth + val.pageNoCount / cmPageNo  档案盒和档案一共占据的宽度
           */
          var width
          if (cmPageNo) {
            // val.allBoxWidth + val.pageNoCount / cmPageNo
            width = new Decimal(val.allBoxWidth).add(
              new Decimal(val.pageNoCount).div(new Decimal(cmPageNo))
            )
          } else {
            width = val.allBoxWidth
          }
          // 除数做判断，不能为0
          const allDivWidth = val.allDivWidth === 0 ? 1 : val.allDivWidth
          return new Decimal(width).div(new Decimal(allDivWidth)).mul(100).toFixed(1)
        }
        // const allDivWidth = val.allDivWidth === 0 ? 1 : val.allDivWidth
        // return new Decimal(val.allBoxWidth).div(new Decimal(allDivWidth)).mul(100).toFixed(1)
      }
    },

    // 计算百分比不能超过90%，防止大于90之后超出屏幕
    lessThan90() {
      return function (val) {
        /**
         * val实际是percentage()的值，也就是已经档案盒已经用的多少
         * 此处用于定位距顶的距离。即top的值，经测试不可以大于10%否则会超出屏幕，所以在此处限制
         * 不能大于10% 不能超过98%
         */
        return (100 - val >= 10 ? 100 - val : 10) <= 98 ? (100 - val >= 10 ? 100 - val : 10) : 98
      }
    },
  },
  watch: {},
  created() { },
  mounted() { },
  methods: {
    changePadio(row) {
      this.openDetail(row, this.colItem)
    },
    submitForm() {
      // 获取数组的最后一位
      const last = this.selectCabinets[this.selectCabinets.length - 1]
      // if (last === '0') {
      //   EventBus.$emit('submitPostion', this.SelectCabintActive, '0')
      //   this.handleClose()
      // } else {
      //   if (this.selectedMJJ.length == 0) {
      //     this.$message({
      //       message: '请选择密集架',
      //       type: 'warning',
      //     })
      //   } else {
      //     EventBus.$emit('submitPostion', this.selectedMJJ, '1')
      //     this.handleClose()
      //   }
      // }
    },
    // 判断是否显示左右面按钮
    isShowLeftAndRight(item) {
      if (this.colItem) {
        if (this.selectedMJJ.length == 1) {
          return item.some((item) => item.colId == this.colItem.colId)
        }
      }
    },
    // 选中整列密集架的方法
    selectCabinet(item) {
      this.zyType = item.zyType
      // 判断再次点击之后取消选中的状态
      if (this.SelectCabintActive && item.deviceId == this.SelectCabintActive.deviceId) {
        this.SelectCabintActive = null
        this.SelectCabintActiveId = null //取消整架的选中
        this.selectCabinets.pop()
      } else {
        this.SelectCabintActive = item
        this.SelectCabintActiveId = item.deviceId
        this.selectCabinets.push('0')
      }
    },
    openDetail(flag, colItem) {
      // 通过监听的方式请求方法
      this.$refs.InventoryColDetails.show(flag, colItem, this.zytypebutton)
    },
    addObject(obj) {
      // 首先，找到所有与 obj.cabinetId 不同的元素并移除它们
      this.selectedMJJ = this.selectedMJJ.filter((item) => item.cabinetId === obj.cabinetId)
      // 然后检查 obj 是否已经存在于数组中
      const exists = this.selectedMJJ.some((item) => item.colId === obj.colId)
      // 如果不存在，则添加 obj 到数组中
      if (exists) {
        this.selectedMJJ.splice(this.selectedMJJ.indexOf(obj), 1)
      } else {
        this.selectedMJJ.push(obj)
      }
    },
    getLocalImageUrl(flag) {
      return flag == 1 ? import('@/assets/mjj_fix.png') : import('@/assets/mjj_p.png')
    },
    // 单击点击事件
    oneSelectMjj(flag, item) {
      event.stopPropagation() //阻止冒泡事件
      this.addObject(item)
      this.zytypebutton = item.zyType
      this.showColItemData = false
      this.SelectCabintActiveId = null
      const result = this.selectedMJJ.some(
        (x) => JSON.stringify(x.colId) === JSON.stringify(item.colId)
      )
      // 判断item与currentIndex ，相同的话，就将currentIndex置空
      if (!result) {
        this.currentIndex = null //取消选中]
        this.selectCabinets.pop()
      } else {
        this.colItem = item
        this.currentIndex = item
        this.selectCabinets.push('1')
      }
      this.upItemWidth = this.getTotalWidth(this.data)
      if (this.UseDetails == 'newInventory') {
        // this.$refs.InventoryColDetails.show(flag, item)
      } else {
        this.$refs.colDetails.show(flag, item, this.zytypebutton)
      }
    },

    getTotalWidth(arr) {
      let totalWidth = 0
      arr.forEach((item) => {
        totalWidth += Number(item.boxWidth)
      })
      return totalWidth
    },
    openDialog(value) {
      this.selectedMJJ = []
      this.SelectCabintActiveId = value
      this.dialogVisible = true
    },
    handleClose() {
      this.dialogVisible = false
      this.$refs.InventoryColDetails.selectedPositions.length = 0
    },
  },
}
</script>
<style lang="less" scoped>
.el-dialog__body {
  max-height: 50vh;
  overflow: hidden;
  /* 溢出隐藏并且加上滚动条 */
  overflow-y: auto;
}

.Select-Cabint-Active,
.cabint:hover {
  background: rgb(219, 218, 218);
}

.cabint-body-center {
  position: relative;
}

.cabint-body {
  .zyTypeButton {
    position: absolute;
    bottom: 50%;
    right: 0;
    z-index: 99;
  }

  .cabint {
    margin: 0 auto 10px;
    height: 80%;
    display: flex;
    justify-content: center;
    position: relative;

    .jiaobiao {
      position: absolute;
      bottom: 0;
      right: 0;
      z-index: 99;
      color: #5a9cf8;
      font-size: 1rem
        /* 60/192 */
      ;
    }

    .mjj-box {
      position: relative;
      width: 0.6rem
        /* 100/192 */
      ;
      margin: 10px 2px;
    }

    .mjj-box::after {
      content: '';
      /* 伪元素必须有内容 */
      position: absolute;
      /* 绝对定位 */
      top: 0;
      /* 与容器顶部对齐 */
      left: 0;
      /* 与容器左侧对齐 */
      width: 100%;
      /* 覆盖图片的宽度 */
      height: 100%;
      /* 覆盖图片的高度 */

      background: linear-gradient(rgba(255, 255, 255, 0) var(--gradient-start),
          rgba(78, 166, 228, 0.6) 0%);
      /* 设置颜色和透明度，这里以半透明红色为例 */
      z-index: 1;
      /* 确保覆盖层在图片之上 */
    }
  }
}

.isActive {
  filter: brightness(80%);
  /* 降低亮度 */
}

.mjj-img {
  position: relative;
  width: 100%;
  height: 100%;
}

.choose {
  position: absolute;
  top: -30px;
  left: 50%;
  transform: translateX(-50%);
  // font-size: 0.17rem /* 16/192 */;
  font-weight: 700;
  z-index: 99;
  color: #7ec050;
}

.mjj-text {
  position: absolute;
  // 垂直水平居中
  left: 50%;
  transform: translate(-50%, -100%);
  font-size: 0.17rem
    /* 16/192 */
  ;
  font-weight: 700;
  // 强制一行展示
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  z-index: 99;
  color: #f2f2f2f2;
}

.heightLight-text {
  // 去除斜体
  font-style: normal;
  color: #15a8ea;
  font-weight: 700;
}
</style>
